/*
Copyright 2021 LuJun

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished 
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

/// <reference path="./net-data.ts" />
/// <reference path="./net-line.ts" />
/// <reference path="../log/log-manager.ts" />
/// <reference path="../utils/js.ts" />

namespace lcc {

const url = require('url');

const TAG = "lcc/network/net-server.ts";

/**
 * @zh
 * 网络服务器tick时间<br/>
 * 服务器上[[NetLine.onUpdate]]的基准时间
 */
export let NETSERVER_TICKTIME = 1;

/**
 * @zh
 * Http的调用方式
 */
export enum HttpCall {
    /**
     * @zh
     * GET方式
     */
    GET = 1,
    
    /**
     * @zh
     * POST方式
     */
	POST,
}

/**
 * @zh
 * 网络服务器映射表
 */
export let NETSERVERS:{[key:string]:NetLine} = js.createMap();

/**
 * @zh
 * 网络连接映射表
 */
export let NETCONNECTIONS:{[key:string]:NetLine} = js.createMap();

/**
 * @zh
 * 网络服务器管理<br/>
 * 监听连接请求端和具体连接的管理
 */
class NetServer extends cocos.event.EventTarget {

	/**
     * @zh
	 * 是否使用网络心跳
	 */
	private _useHeart:boolean = false;

    /**
     * @zh
     * 连接线序号<br/>
     * 新的连接名称通过这个序号区别
     */
    private _connectIndex:number = 0;

	/**
     * @zh
	 * 安装心跳
	 */
	private setupHeartTick(){
		if(!this._useHeart && (!js.isEmptyMap(NETSERVERS) || !js.isEmptyMap(NETCONNECTIONS))){
			timerMgr.addTimer(NETSERVER_TICKTIME, this.onHeartTick.bind(this),{
                group : "lcc.NetServer", 
                key : "tick",
                loop : true
            });
			this._useHeart = true;
			DEBUG.NETWORK && logMgr.debug(TAG, `setupHeartTick tick ${NETSERVER_TICKTIME}`);
		}
	}

	/**
     * @zh
	 * 删除心跳
	 */
	private deleteHeartTick(){
		if(this._useHeart && js.isEmptyMap(NETSERVERS) && js.isEmptyMap(NETCONNECTIONS)){
			timerMgr.removeTimer({
                group : "lcc.NetServer", 
                key : "tick"
            });
			this._useHeart = false;
			DEBUG.NETWORK && logMgr.debug(TAG, `deleteHeartTick tick`);
		}
	}
    
	/**
     * @zh
	 * 当心跳回调
     * 
     * @param dt 间隔时间，一般为`NETSERVER_TICKTIME`
	 */
	private onHeartTick(dt:number){
		for (let cname of Object.keys(NETSERVERS)){
			let netline = NETSERVERS[cname];
			if(netline){
				netline.onUpdate(dt);
			}
		}
		for (let cname of Object.keys(NETCONNECTIONS)){
			let netline = NETCONNECTIONS[cname];
			if(netline){
				netline.onUpdate(dt);
			}
		}
	}
    
    /**
     * @zh
	 * 添加服务器<br/>
     * 这里只是添加服务器，如果你需要启动服务器，应该手动调用`open`<br/>
     * ```
     *      let server = lcc.netServer.addServer(...);
     *      if(server){
     *          // 打开服务器，一般就是启动了监听
     *          server.open();
     *      }
     * ```
     * 
	 * @param name - 名称
	 * @param type - 类型
	 * @param config - 配置
	 */
    public addServer(name:string, type:NetLineType, config:{[key:string]:any} = js.createMap()){
		DEBUG.NETWORK && logMgr.debug(TAG, `addServer ${name} ${type} ${JSON.stringify(config)}`);
        if(NETSERVERS[name]){
			logMgr.error(TAG, `server [${name}] conflict!`);
		}else{
			let netType = NetLine.getNetType(type);
			if(!netType){
				logMgr.error(TAG, `net type [${type}] not found!`);
			}else{
				let netline = new netType(name, NetLineMode.SERVER, type);
				netline.config(config);
				NETSERVERS[name] = netline;
				this.setupHeartTick();
				DEBUG.NETWORK && logMgr.debug(TAG, `addServer ${name} success`);
				return netline;
			}
        }
	}

	/**
     * @zh
	 * 获得服务器
     * 
	 * @param name - 名称
     * 
     * @returns 服务器对象
	 */
	public getServer(name:string){
		return NETSERVERS[name];
	}

	/**
     * @zh
	 * 移除服务器
     * 
	 * @param name - 名称
	 */
	public removeServer(name:string){
		DEBUG.NETWORK && logMgr.debug(TAG, `removeServer ${name}`);
		let netline = NETSERVERS[name];
		if(netline){
			delete NETSERVERS[name];
			this.deleteHeartTick();
			netline.close();
			DEBUG.NETWORK && logMgr.debug(TAG, `removeServer ${name} success`);
		}
	}

	/**
	 * @zh
	 * 移除所有服务器
	 */
	public removeAllServers(){
		for(let sname of Object.keys(NETSERVERS)){
			this.removeServer(sname);
		}
	}
	
	/**
     * @zh
	 * 新连接名称<br/>
     * 这个由框架使用
     * 
     * @returns 可使用的连接名称
     * 
     * @internal 
	 */
	public _newConnectName(){
        return `${BOOT_TIME}-${this._connectIndex ++}`;
	}
    
    /**
     * @zh
     * 添加连接线<br/>
     * 这个由框架使用
     * 
     * @param netline - 网络线对象
     * 
     * @internal 
     */
    public _addConnectLine(netline:NetLine){
		DEBUG.NETWORK && logMgr.debug(TAG, `_addConnectLine ${netline.getName()}`);
		if(netline){
			let name = netline.getName();
			if(NETCONNECTIONS[name]){
				logMgr.error(TAG, `connect name [${name}] conflict!`);
			}else{
				NETCONNECTIONS[name] = netline;
				this.setupHeartTick();
				DEBUG.NETWORK && logMgr.debug(TAG, `_addConnectLine ${name} success`);
			}
		}
    }
	
    /**
     * @zh
     * 获得连接线
     * 
     * @param name - 名称
     * 
     * @internal 
     */
    public _getConnectLine(name:string){
        return NETCONNECTIONS[name];
    }

    /**
     * @zh
     * 移除连接线
     * 
     * @param name - 名称
     * 
     * @internal 
     */
    public _removeConnectLine(name:string){
		DEBUG.NETWORK && logMgr.debug(TAG, `_removeConnectLine ${name}`);
        let netline = NETCONNECTIONS[name];
		if(netline){
			delete NETCONNECTIONS[name];
			this.deleteHeartTick();
			netline.close();
            DEBUG.NETWORK && logMgr.debug(TAG, `_removeConnectLine ${name} success`);
		}
    }

    /**
     * @zh
     * 移除服务器线上的所有连接线
     * 
     * @param svrline - 服务器线
     * 
     * @internal 
     */
    public _removeConnectLines(svrline:NetLine){
		DEBUG.NETWORK && logMgr.debug(TAG, `_removeConnectLines server ${svrline.getName()}`);
        for (let cname of Object.keys(NETCONNECTIONS)){
            let netline = NETCONNECTIONS[cname];
            if(netline.getParent() === svrline){
                this._removeConnectLine(cname);
            }
		}
		DEBUG.NETWORK && logMgr.debug(TAG, `_removeConnectLines server ${svrline.getName()} success`);
    }

    /**
     * @zh
     * 当接收到Http请求
     * 
     * @param req - 请求对象
     * @param res - 回应对象
     * @param method - 调用方式
     * 
     * @internal 
     */
    public _onHttpRequest(req:any, res:any, method:HttpCall){
		DEBUG.NETWORK && logMgr.debug(TAG, `_onHttpRequest server ${req.app.get('server')} ${method}`);
        const sname = req.app.get('server');
        let r:any;
        if(method == HttpCall.POST){
			r = req.body.data;
		}else{	// GET
			let query = url.parse(req.url,true).query
			r = query.data;
        }
		let netData:NetData = r && unpackNetData(Buffer.from(r, 'base64'));
        let server = this.getServer(sname);
        if(server && server.getType() == NetLineType.HTTP){
            DEBUG.NETWORK && logMgr.debug(TAG, `_onHttpRequest server ${sname} ${JSON.stringify(netData)} success`);
			server._onRecvNetData(netData, { response : res });
        }else{
            logMgr.error(TAG, `http Server ${sname} not found!`);
        }
    }
}

/**
 * @zh
 * 网络服务器管理实例
 */
export const netServer = new NetServer();

}
